// pages/math1/math1.js
var app = getApp();
Page({
  data: {
    index:0,//题目序号
    chooseValue: [], // 输入的答案序列
    totalScore:100,//总分
    wrong: 0, // 错误的题目数量
    wrongList: [], // 错误的题目集合-乱序
    wrongListSort: [], // 错误的题目集合-正序
    num:0,//题目数量
    result1: 0,
    result11:null,
    focusInput: false,
    currentWord: {}, //当前显示的单词对象
    favoriteWords: [], // 存储收藏的单词
    wrongques:[],//存储错题
    isFavorited: false, // 是否已收藏
  },
  //生命周期函数--监听页面加载
  onLoad(options) {
    const favoriteWords = wx.getStorageSync('favoriteWords') || [];
    const wrongques = wx.getStorageSync('wrongques') || [];
    this.setData({ favoriteWords });
    this.setData({ wrongques });
    this.checkIfFavorited(); // 检查当前题目是否已收藏
    console.log(options);
    wx.setNavigationBarTitle({
        title: options.testId === 'math1' ? '一年级题目' : 
               options.testId === 'math2' ? '二年级题目' : 
               options.testId === 'math3' ? '三年级题目' : '默认标题'
    }); // 动态设置导航条标题 
    this.setData({
      questionList: app.globalData.questionList[options.testId],  // 拿到答题数据
      testId: options.testId // 课程ID
    })
    console.log(this.data.questionList);
    
    let count = this.generateArray(0, this.data.questionList.length-1); // 生成题序
    this.data.num = options.number;  // 102/301-302 试题有20道题
    this.setData({
      shuffleIndex: this.shuffle(count).slice(0, this.data.num) // 生成随机题序 [2,0,3] 并截取num道题
    })
    this.showWord(); // 加载题目 
  },
  showWord: function() {
    console.log("加载题目");
    var word = this.data.questionList[this.data.shuffleIndex[this.data.index]];
    // 更新当前显示的题目数据
    this.setData({
        currentWord: word, // 保存当前展示的题目对象
        isFavorited: false // 每次加载新题目时默认未收藏
    });
    // 检查新题目是否已收藏并更新收藏状态
    this.checkIfFavorited();
  },
  // 检查当前题目是否已收藏
  checkIfFavorited: function() {
    const { currentWord, favoriteWords } = this.data;
    const isFavorited = favoriteWords.some(word => word.no === currentWord.no);
    this.setData({ isFavorited });
  },
  toggleFavorite: function() {
    const { currentWord, favoriteWords, isFavorited } = this.data;

    if (isFavorited) {
      // 如果已收藏，取消收藏
      console.log("已收藏，取消收藏");
      const updatedFavorites = favoriteWords.filter(word => word.no !== currentWord.no);
      this.setData({ 
        favoriteWords: updatedFavorites, 
        isFavorited: false 
      });
      wx.setStorageSync('favoriteWords', updatedFavorites); // 更新本地存储
      wx.showToast({ title: '已取消收藏', icon: 'none' });
    } else {
      // 如果未收藏，添加收藏
      console.log("未收藏，添加收藏");
      favoriteWords.push(currentWord);
      this.setData({ 
        favoriteWords, 
        isFavorited: true 
      });
      wx.setStorageSync('favoriteWords', favoriteWords); // 更新本地存储
      wx.showToast({ title: '已收藏', icon: 'success' });
    }
  },
  //数组乱序/洗牌
 shuffle: function (arr) {
    let i = arr.length;
    while (i) {
      let j = Math.floor(Math.random() * i--);
      [arr[j], arr[i]] = [arr[i], arr[j]];
    }
    return arr;
  },
  //退出答题 按钮
 outTest: function(){
    wx.showModal({
      title: '提示',
      content: '你真的要退出答题吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.reLaunch({
            url: '../mathhome/mathhome'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //下一题/提交 按钮
 result11: function (e) {
    this.data.chooseValue[this.data.index] = e.detail.value;
    this.setData({
        result11: e.detail.value
    })
 },
 nextSubmit: function(){
    // 判断答案是否正确
    this.chooseError();
    // 判断是不是最后一题
    if (this.data.index < this.data.shuffleIndex.length - 1) {
      // 渲染下一题
      this.setData({
        index: this.data.index + 1
      });
      this.showWord(); // 显示下一个随机题目
      this.setData({
        result11: '',
        focusInput: true // 设置为 true 以保持焦点状态
      });
    } else {
      let wrongList = JSON.stringify(this.data.wrongList);
      let wrongListSort = JSON.stringify(this.data.wrongListSort);
      let chooseValue = JSON.stringify(this.data.chooseValue);
      wx.navigateTo({
        url: '../results/results?totalScore=' + this.data.totalScore + '&wrongList=' + wrongList + '&chooseValue=' + chooseValue + '&wrongListSort=' + wrongListSort + '&testId=' + this.data.testId
      })

      // 设置缓存
      var logs = wx.getStorageSync('logs') || []
      let logsList = { "date": Date.now(), "testId": this.data.testId, "score": this.data.totalScore ,"number":this.data.num}
      logs.unshift(logsList);
      wx.setStorageSync('logs', logs);
    }
  },
  //错题处理
 chooseError: function(){
    var trueValue = this.data.questionList[this.data.shuffleIndex[this.data.index]]['answer'];
    var chooseVal = this.data.result11;
    console.log('选择了' + chooseVal + '答案是' + trueValue);
    if (chooseVal != trueValue) {
      console.log('错了');
      this.data.wrong++;
      this.data.wrongListSort.push(this.data.index);
      this.data.wrongList.push(this.data.shuffleIndex[this.data.index]);
      this.setData({
        totalScore: this.data.totalScore - (100/this.data.num)// 扣分操作
      })
      const { currentWord, wrongques } = this.data;
      const iswrong = wrongques.some(word => word.no === currentWord.no);
      if(iswrong);
      else{
        /*// 创建一个新的 wrong 对象
        const newWrong = { ...currentWord }; // 复制 currentWord 对象
        // 检查 wrongques 中最后一项是否存在，如果不存在，则创建一个新的队列
        if (wrongques.length === 0 || !Array.isArray(wrongques[wrongques.length - 1].queue)) {
            wrongques.push({ queue: [] });
        }
        // 将 chooseVal 推入最后一项队列中
        wrongques[wrongques.length - 1].queue.push('chooseVal');*/
        // 设置新的数据对象，包括更新后的 wrongques
        // 创建一个新的 wrong 对象，将 chooseVal 添加到该对象中
        const wrong = {
            ...currentWord,
            chooseVal: chooseVal
        };
  
        // 将新的 wrong 对象添加到 wrongques 数组中
        wrongques.push(wrong);
        this.setData({
            wrongques
        });
        wx.setStorageSync('wrongques', wrongques); // 更新本地存储
      }
    }
  },
  /**
     * 生成一个从 start 到 end 的连续数组
     * @param start
     * @param end
     */
  generateArray: function(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start)
  }
})